package me.boot.db.mybatis.handler;

import me.base.utils.enums.DbEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Description:
 * @author: Sylar
 * @date: 2021年10月06日 5:13 下午
 */
@MappedJdbcTypes(value = JdbcType.TINYINT, includeNullJdbcType = true)
public class BaseEnumTypeHandler extends BaseTypeHandler<DbEnum> {

    private Class<DbEnum> type;

    public BaseEnumTypeHandler() {
    }

    public BaseEnumTypeHandler(Class<DbEnum> type) {
        if (type == null) throw new IllegalArgumentException("Type argument cannot be null");
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, DbEnum dbEnum, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, dbEnum.getValue());
    }

    @Override
    public DbEnum getNullableResult(ResultSet rs, String s) throws SQLException {
        return convert(rs.getInt(s));
    }

    @Override
    public DbEnum getNullableResult(ResultSet rs, int i) throws SQLException {
        return convert(rs.getInt(i));
    }

    @Override
    public DbEnum getNullableResult(CallableStatement cs, int i) throws SQLException {
        return convert(cs.getInt(i));
    }

    private DbEnum convert(int value) {
        DbEnum[] objs = type.getEnumConstants();
        for (DbEnum em : objs) {
            if (em.getValue() == value) {
                return em;
            }
        }
        return null;
    }
}
